# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def __init__(self):
        self.inlist = []

    def isValidBST(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: bool
        """
        if not root:
            return False
        if self.loop(root) is False:
            return False
        else:
            return True

    def loop(self, node):
        if not node:
            return
        if self.loop(node.left) is False:
            return False
        if self.inlist:
            if node.val > self.inlist[-1]:
                self.inlist.append(node.val)
            else:
                return False
        else:
            self.inlist.append(node.val)
        if self.loop(node.right) is False:
            return False

